package com.atguigu.springcloud.order.controller;

import com.atguigu.springcloud.framework.common.api.ApiResult;
import com.atguigu.springcloud.order.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author lenovo
 * @version 1.0
 * @date 2020/11/12 9:58
 */
@RestController
@Slf4j
@RequestMapping("consumer")
public class OrderController {

    //    private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private LoadBalancer loadBalancer;


    @GetMapping("/payment/get/{id}")
    public ApiResult getPayment(@PathVariable Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, ApiResult.class);
    }

    @GetMapping("/payment/getForEntity/{id}")
    public ApiResult getForEntity(@PathVariable Long id) {
        ResponseEntity<ApiResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, ApiResult.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        }
        return ApiResult.fail(forEntity.getStatusCode().toString());
    }


    /**
     * 自定义IRule策略实现（手写轮询算法）
     *
     * @return
     */
    @GetMapping("/payment/lb")
    public Object discovery() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance instance = loadBalancer.serviceInstance(instances);
        return instance;

    }


    @GetMapping("/payment/zipkin")
    public String getZipkin() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);
    }

}
